<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Onepay extends CI_Controller {  
    public function index() {
        $this->load->view('webservice/onepay/index');    
    }  
   
    public function call_onepay() {
        if($_POST['type_card'] == 1) {
            $this->do_noi_dia();
        } else {
            $this->do_quoc_te();
        }
    }
   
   
    public function do_noi_dia() {
        
        $_POST['virtualPaymentClientURL'] = 'http://mtf.onepay.vn/onecomm-pay/vpc.op';
        $_POST['vpc_Merchant'] = 'ONEPAY';
        $_POST['vpc_AccessCode'] = 'D67342C2';
        $_POST['vpc_MerchTxnRef'] = date ( 'YmdHis' ) . rand ();
        $_POST['vpc_OrderInfo'] = 'JSECURETEST01';      // Tên hóa đơn - (tối đa 34 ký tự)
        $_POST['vpc_ReturnURL'] = base_url('webservice/onepay/dr_noi_dia');
        $_POST['vpc_Version'] = '2';
        $_POST['vpc_Command'] = 'pay';
        $_POST['vpc_Locale'] = 'vn';
        $_POST['vpc_Currency'] = 'VND';
        
        $_POST['vpc_TicketNo'] = $_SERVER ['REMOTE_ADDR'];
        $_POST['vpc_SHIP_Street01'] = '39A Ngo Quyen';
        $_POST['vpc_SHIP_Provice'] = 'Hoan Kiem';
        $_POST['vpc_SHIP_City'] = 'Ha Noi';
        $_POST['vpc_SHIP_Country'] = 'Viet Nam';
        $_POST['vpc_Customer_Phone'] = '840904280949';
        $_POST['vpc_Customer_Email'] = 'support@onepay.vn';
        $_POST['vpc_Customer_Id'] = 'thanhvt';
        
        // Define Constants
        // ----------------
        // This is secret for encoding the MD5 hash
        // This secret will vary from merchant to merchant
        // To not create a secure hash, let SECURE_SECRET be an empty string - ""
        // $SECURE_SECRET = "secure-hash-secret";
        // Khóa bí mật - được cấp bởi OnePAY
        $SECURE_SECRET = "A3EFDFABA8653DF2342E8DAC29B51AF0";
        
        // add the start of the vpcURL querystring parameters
        // *****************************Lấy giá trị url cổng thanh toán*****************************
        $vpcURL = $_POST["virtualPaymentClientURL"] . "?";
        
        // Remove the Virtual Payment Client URL from the parameter hash as we 
        // do not want to send these fields to the Virtual Payment Client.
        // bỏ giá trị url và nút submit ra khỏi mảng dữ liệu
        unset($_POST["virtualPaymentClientURL"]); 
        unset($_POST["SubButL"]);
        
        //$stringHashData = $SECURE_SECRET; *****************************Khởi tạo chuỗi dữ liệu mã hóa trống*****************************
        $stringHashData = "";
        // sắp xếp dữ liệu theo thứ tự a-z trước khi nối lại
        // arrange array data a-z before make a hash
        ksort ($_POST);
        
        // set a parameter to show the first pair in the URL
        // đặt tham số đếm = 0
        $appendAmp = 0;
        
        foreach($_POST as $key => $value) {
            // create the md5 input and URL leaving out any fields that have no value
            // tạo chuỗi đầu dữ liệu những tham số có dữ liệu
            if (strlen($value) > 0) {
                // this ensures the first paramter of the URL is preceded by the '?' char
                if ($appendAmp == 0) {
                    $vpcURL .= urlencode($key) . '=' . urlencode($value);
                    $appendAmp = 1;
                } else {
                    $vpcURL .= '&' . urlencode($key) . "=" . urlencode($value);
                }
                //$stringHashData .= $value; *****************************sử dụng cả tên và giá trị tham số để mã hóa*****************************
                if ((strlen($value) > 0) && ((substr($key, 0,4)=="vpc_") || (substr($key,0,5) =="user_"))) {
        		    $stringHashData .= $key . "=" . $value . "&";
        		}
            }
        }
        //*****************************xóa ký tự & ở thừa ở cuối chuỗi dữ liệu mã hóa*****************************
        $stringHashData = rtrim($stringHashData, "&");
        // Create the secure hash and append it to the Virtual Payment Client Data if
        // the merchant secret has been provided.
        // thêm giá trị chuỗi mã hóa dữ liệu được tạo ra ở trên vào cuối url
        if (strlen($SECURE_SECRET) > 0) {
            //$vpcURL .= "&vpc_SecureHash=" . strtoupper(md5($stringHashData));
            // *****************************Thay hàm mã hóa dữ liệu*****************************
            $vpcURL .= "&vpc_SecureHash=" . strtoupper(hash_hmac('SHA256', $stringHashData, pack('H*',$SECURE_SECRET)));
        }
        
        // FINISH TRANSACTION - Redirect the customers using the Digital Order
        // ===================================================================
        // chuyển trình duyệt sang cổng thanh toán theo URL được tạo ra
        header("Location: ".$vpcURL);
    }
    
    public function dr_noi_dia() {
        // Define Constants
        // ----------------
        // This is secret for encoding the MD5 hash
        // This secret will vary from merchant to merchant
        // To not create a secure hash, let SECURE_SECRET be an empty string - ""
        // $SECURE_SECRET = "secure-hash-secret";
        $SECURE_SECRET = "A3EFDFABA8653DF2342E8DAC29B51AF0";
        
        // If there has been a merchant secret set then sort and loop through all the
        // data in the Virtual Payment Client response. While we have the data, we can
        // append all the fields that contain values (except the secure hash) so that
        // we can create a hash and validate it against the secure hash in the Virtual
        // Payment Client response.
        
        
        // NOTE: If the vpc_TxnResponseCode in not a single character then
        // there was a Virtual Payment Client error and we cannot accurately validate
        // the incoming data from the secure hash. */
        
        // get and remove the vpc_TxnResponseCode code from the response fields as we
        // do not want to include this field in the hash calculation
        $vpc_Txn_Secure_Hash = $_GET ["vpc_SecureHash"];
        unset ( $_GET ["vpc_SecureHash"] );
        
        // set a flag to indicate if hash has been validated
        $errorExists = false;
        
        if (strlen ( $SECURE_SECRET ) > 0 && $_GET ["vpc_TxnResponseCode"] != "7" && $_GET ["vpc_TxnResponseCode"] != "No Value Returned") {
        	
            //$stringHashData = $SECURE_SECRET;
            //*****************************khởi tạo chuỗi mã hóa rỗng*****************************
            $stringHashData = "";
        	
        	// sort all the incoming vpc response fields and leave out any with no value
        	foreach ( $_GET as $key => $value ) {
        //        if ($key != "vpc_SecureHash" or strlen($value) > 0) {
        //            $stringHashData .= $value;
        //        }
        //      *****************************chỉ lấy các tham số bắt đầu bằng "vpc_" hoặc "user_" và khác trống và không phải chuỗi hash code trả về*****************************
                if ($key != "vpc_SecureHash" && (strlen($value) > 0) && ((substr($key, 0,4)=="vpc_") || (substr($key,0,5) =="user_"))) {
        		    $stringHashData .= $key . "=" . $value . "&";
        		}
        	}
        //  *****************************Xóa dấu & thừa cuối chuỗi dữ liệu*****************************
            $stringHashData = rtrim($stringHashData, "&");	
        	
        	
        //    if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper ( md5 ( $stringHashData ) )) {
        //    *****************************Thay hàm tạo chuỗi mã hóa*****************************
        	if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper(hash_hmac('SHA256', $stringHashData, pack('H*',$SECURE_SECRET)))) {
        		// Secure Hash validation succeeded, add a data field to be displayed
        		// later.
        		$hashValidated = "CORRECT";
        	} else {
        		// Secure Hash validation failed, add a data field to be displayed
        		// later.
        		$hashValidated = "INVALID HASH";
        	}
        } else {
        	// Secure Hash was not validated, add a data field to be displayed later.
        	$hashValidated = "INVALID HASH";
        }
        
        // Define Variables
        // ----------------
        // Extract the available receipt fields from the VPC Response
        // If not present then let the value be equal to 'No Value Returned'
        // Standard Receipt Data
        $amount = $this->_null2unknown ( $_GET ["vpc_Amount"] );
        $locale = $this->_null2unknown ( $_GET ["vpc_Locale"] );
        //$batchNo = null2unknown ( $_GET ["vpc_BatchNo"] );
        $command = $this->_null2unknown ( $_GET ["vpc_Command"] );
        //$message = null2unknown ( $_GET ["vpc_Message"] );
        $version = $this->_null2unknown ( $_GET ["vpc_Version"] );
        //$cardType = null2unknown ( $_GET ["vpc_Card"] );
        $orderInfo = $this->_null2unknown ( $_GET ["vpc_OrderInfo"] );
        //$receiptNo = null2unknown ( $_GET ["vpc_ReceiptNo"] );
        $merchantID = $this->_null2unknown ( $_GET ["vpc_Merchant"] );
        //$authorizeID = null2unknown ( $_GET ["vpc_AuthorizeId"] );
        $merchTxnRef = $this->_null2unknown ( $_GET ["vpc_MerchTxnRef"] );
        $transactionNo = $this->_null2unknown ( $_GET ["vpc_TransactionNo"] );
        //$acqResponseCode = null2unknown ( $_GET ["vpc_AcqResponseCode"] );
        $txnResponseCode = $this->_null2unknown ( $_GET ["vpc_TxnResponseCode"] );
        
        // This is the display title for 'Receipt' page 
        //$title = $_GET ["Title"];
        
        $transStatus = "";
        if($hashValidated=="CORRECT" && $txnResponseCode=="0"){
        	$transStatus = "Giao dịch thành công";
        }elseif ($hashValidated=="INVALID HASH" && $txnResponseCode=="0"){
        	$transStatus = "Giao dịch Pendding";
        }else {
        	$transStatus = "Giao dịch thất bại";
        }
        
        $data['responseMessage'] = $this->_getResponseDescription($txnResponseCode);
        $data['transactionNo'] = $transactionNo;
        $data['message'] = 'aaaaaaaaaaaaa';
        $data['txnResponseCode'] = $txnResponseCode;
        $data['amount'] = $amount;
        $data['orderInfo'] = $orderInfo;
        $data['merchTxnRef'] = $merchTxnRef;
        $data['transStatus'] = $transStatus;
        $data['merchantID'] = $merchantID;
        
        if($hashValidated=="CORRECT" && $txnResponseCode=="0"){
            $this->load->model(array('usermodel', 'eventmodel'));
            $_SESSION['userLoggedIn']['point'] += $amount;
            $this->usermodel->update($_SESSION['userLoggedIn']['id'], array('point' => $_SESSION['userLoggedIn']['point']));
        }
        $this->session->set_flashdata('message', $transStatus);
        
        redirect('user/recharge');
    }
    
    // If input is null, returns string "No Value Returned", else returns input
    private function _null2unknown($data) {
    	if ($data == "") {
    		return "No Value Returned";
    	} else {
    		return $data;
    	}
    }
    
    // This method uses the QSI Response code retrieved from the Digital
    // Receipt and returns an appropriate description for the QSI Response Code
    //
    // @param $responseCode String containing the QSI Response Code
    //
    // @return String containing the appropriate description
    //
     private  function _getResponseDescription($responseCode) {
    	switch ($responseCode) {
    		case "0" :
    			$result = "Giao dịch thành công - Approved";
    			break;
    		case "1" :
    			$result = "Ngân hàng từ chối giao dịch - Bank Declined";
    			break;
    		case "3" :
    			$result = "Mã đơn vị không tồn tại - Merchant not exist";
    			break;
    		case "4" :
    			$result = "Không đúng access code - Invalid access code";
    			break;
    		case "5" :
    			$result = "Số tiền không hợp lệ - Invalid amount";
    			break;
    		case "6" :
    			$result = "Mã tiền tệ không tồn tại - Invalid currency code";
    			break;
    		case "7" :
    			$result = "Lỗi không xác định - Unspecified Failure ";
    			break;
    		case "8" :
    			$result = "Số thẻ không đúng - Invalid card Number";
    			break;
    		case "9" :
    			$result = "Tên chủ thẻ không đúng - Invalid card name";
    			break;
    		case "10" :
    			$result = "Thẻ hết hạn/Thẻ bị khóa - Expired Card";
    			break;
    		case "11" :
    			$result = "Thẻ chưa đăng ký sử dụng dịch vụ - Card Not Registed Service(internet banking)";
    			break;
    		case "12" :
    			$result = "Ngày phát hành/Hết hạn không đúng - Invalid card date";
    			break;
    		case "13" :
    			$result = "Vượt quá hạn mức thanh toán - Exist Amount";
    			break;
    		case "21" :
    			$result = "Số tiền không đủ để thanh toán - Insufficient fund";
    			break;
    		case "99" :
    			$result = "Người sủ dụng hủy giao dịch - User cancel";
    			break;
    		default :
    			$result = "Giao dịch thất bại - Failured";
    	}
    	return $result;
    }
    
    public function do_quoc_te() {
      
        $_POST['virtualPaymentClientURL'] = 'http://mtf.onepay.vn/vpcpay/vpcpay.op';
        $_POST['vpc_Merchant'] = 'TESTONEPAY';
        $_POST['vpc_AccessCode'] = '6BEB2546';
        $_POST['vpc_MerchTxnRef'] = date ( 'YmdHis' ) . rand ();
        $_POST['vpc_OrderInfo'] = 'JSECURETEST01';      // Tên hóa đơn - (tối đa 34 ký tự)
        $_POST['vpc_ReturnURL'] = base_url('webservice/onepay/dr_quoc_te');
        $_POST['vpc_Version'] = '2';
        $_POST['vpc_Command'] = 'pay';
        $_POST['vpc_Locale'] = 'en';
        
        $_POST['vpc_TicketNo'] = $_SERVER ['REMOTE_ADDR'];
        $_POST['vpc_SHIP_Street01'] = '39A Ngo Quyen';
        $_POST['vpc_SHIP_Provice'] = 'Hoan Kiem';
        $_POST['vpc_SHIP_City'] = 'Ha Noi';
        $_POST['vpc_SHIP_Country'] = 'Viet Nam';
        $_POST['vpc_Customer_Phone'] = '840904280949';
        $_POST['vpc_Customer_Email'] = 'support@onepay.vn';
        $_POST['vpc_Customer_Id'] = 'thanhvt';
        
        $_POST['AVS_Street01'] = '194 Tran Quang Khai';
        $_POST['AVS_City'] = 'Hanoi';
        $_POST['AVS_StateProv'] = 'Hoan Kiem';
        $_POST['AVS_PostCode'] = '10000';
        //$_POST['AVS_Country'] = 'VN';
        $_POST['display'] = '';
        
        $_POST['Title'] = 'VPC+3-Party';
      
        unset($_POST['type_card']);
        
        // Define Constants
        // ----------------
        // This is secret for encoding the MD5 hash
        // This secret will vary from merchant to merchant
        // To not create a secure hash, let SECURE_SECRET be an empty string - ""
        // $SECURE_SECRET = "secure-hash-secret";
        $SECURE_SECRET = "6D0870CDE5F24F34F3915FB0045120DB";
        
        // add the start of the vpcURL querystring parameters
        $vpcURL = $_POST["virtualPaymentClientURL"] . "?";
        
        // Remove the Virtual Payment Client URL from the parameter hash as we 
        // do not want to send these fields to the Virtual Payment Client.
        unset($_POST["virtualPaymentClientURL"]); 
        
        // The URL link for the receipt to do another transaction.
        // Note: This is ONLY used for this example and is not required for 
        // production code. You would hard code your own URL into your application.
        
        // Get and URL Encode the AgainLink. Add the AgainLink to the array
        // Shows how a user field (such as application SessionIDs) could be added
        $_POST['AgainLink']=urlencode($_SERVER['HTTP_REFERER']);
        //$_POST['AgainLink']=urlencode($_SERVER['HTTP_REFERER']);
        // Create the request to the Virtual Payment Client which is a URL encoded GET
        // request. Since we are looping through all the data we may as well sort it in
        // case we want to create a secure hash and add it to the VPC data if the
        // merchant secret has been provided.
        //$md5HashData = $SECURE_SECRET; Khởi tạo chuỗi dữ liệu mã hóa trống
        $md5HashData = "";
        
        ksort ($_POST);
        
        // set a parameter to show the first pair in the URL
        $appendAmp = 0;
        
        foreach($_POST as $key => $value) {
        
            // create the md5 input and URL leaving out any fields that have no value
            if (strlen($value) > 0) {
                
                // this ensures the first paramter of the URL is preceded by the '?' char
                if ($appendAmp == 0) {
                    $vpcURL .= urlencode($key) . '=' . urlencode($value);
                    $appendAmp = 1;
                } else {
                    $vpcURL .= '&' . urlencode($key) . "=" . urlencode($value);
                }
                //$md5HashData .= $value; sử dụng cả tên và giá trị tham số để mã hóa
                if ((strlen($value) > 0) && ((substr($key, 0,4)=="vpc_") || (substr($key,0,5) =="user_"))) {
        		    $md5HashData .= $key . "=" . $value . "&";
        		}
            }
        }
        //xóa ký tự & ở thừa ở cuối chuỗi dữ liệu mã hóa
        $md5HashData = rtrim($md5HashData, "&");
        // Create the secure hash and append it to the Virtual Payment Client Data if
        // the merchant secret has been provided.
        if (strlen($SECURE_SECRET) > 0) {
            //$vpcURL .= "&vpc_SecureHash=" . strtoupper(md5($md5HashData));
            // Thay hàm mã hóa dữ liệu
            $vpcURL .= "&vpc_SecureHash=" . strtoupper(hash_hmac('SHA256', $md5HashData, pack('H*',$SECURE_SECRET)));
        }
        
        // FINISH TRANSACTION - Redirect the customers using the Digital Order
        // ===================================================================
        //echo $vpcURL;die;
        header("Location: ".$vpcURL);
    }
    
    public function dr_quoc_te() {
        // Define Constants
        // ----------------
        // This is secret for encoding the MD5 hash
        // This secret will vary from merchant to merchant
        // To not create a secure hash, let SECURE_SECRET be an empty string - ""
        // $SECURE_SECRET = "secure-hash-secret";
        $SECURE_SECRET = "6D0870CDE5F24F34F3915FB0045120DB";
        
        // get and remove the vpc_TxnResponseCode code from the response fields as we
        // do not want to include this field in the hash calculation
        $vpc_Txn_Secure_Hash = $_GET["vpc_SecureHash"];
        $vpc_MerchTxnRef = $_GET["vpc_MerchTxnRef"];
        $vpc_AcqResponseCode = $_GET["vpc_AcqResponseCode"];
        unset($_GET["vpc_SecureHash"]);
        // set a flag to indicate if hash has been validated
        $errorExists = false;
        
        if (strlen($SECURE_SECRET) > 0 && $_GET["vpc_TxnResponseCode"] != "7" && $_GET["vpc_TxnResponseCode"] != "No Value Returned") {
        
            ksort($_GET);
            //$md5HashData = $SECURE_SECRET;
            //khởi tạo chuỗi mã hóa rỗng
            $md5HashData = "";
            // sort all the incoming vpc response fields and leave out any with no value
            foreach ($_GET as $key => $value) {
        //        if ($key != "vpc_SecureHash" or strlen($value) > 0) {
        //            $md5HashData .= $value;
        //        }
        //      chỉ lấy các tham số bắt đầu bằng "vpc_" hoặc "user_" và khác trống và không phải chuỗi hash code trả về
                if ($key != "vpc_SecureHash" && (strlen($value) > 0) && ((substr($key, 0,4)=="vpc_") || (substr($key,0,5) =="user_"))) {
        		    $md5HashData .= $key . "=" . $value . "&";
        		}
            }
        //  Xóa dấu & thừa cuối chuỗi dữ liệu
            $md5HashData = rtrim($md5HashData, "&");
        
        //    if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper ( md5 ( $md5HashData ) )) {
        //    Thay hàm tạo chuỗi mã hóa
        	if (strtoupper ( $vpc_Txn_Secure_Hash ) == strtoupper(hash_hmac('SHA256', $md5HashData, pack('H*',$SECURE_SECRET)))) {
                // Secure Hash validation succeeded, add a data field to be displayed
                // later.
                $hashValidated = "CORRECT";
            } else {
                // Secure Hash validation failed, add a data field to be displayed
                // later.
                $hashValidated = "INVALID HASH";
            }
        } else {
            // Secure Hash was not validated, add a data field to be displayed later.
            $hashValidated = "INVALID HASH";
        }
        
        // Define Variables
        // ----------------
        // Extract the available receipt fields from the VPC Response
        // If not present then let the value be equal to 'No Value Returned'
        
        // Standard Receipt Data
        $amount = $this->_null2unknown($_GET["vpc_Amount"]);
        $locale = $this->_null2unknown($_GET["vpc_Locale"]);
        $batchNo = $this->_null2unknown($_GET["vpc_BatchNo"]);
        $command = $this->_null2unknown($_GET["vpc_Command"]);
        $message = $this->_null2unknown($_GET["vpc_Message"]);
        $version = $this->_null2unknown($_GET["vpc_Version"]);
        $cardType = $this->_null2unknown($_GET["vpc_Card"]);
        $orderInfo = $this->_null2unknown($_GET["vpc_OrderInfo"]);
        $receiptNo = $this->_null2unknown($_GET["vpc_ReceiptNo"]);
        $merchantID = $this->_null2unknown($_GET["vpc_Merchant"]);
        //$authorizeID = null2unknown($_GET["vpc_AuthorizeId"]);
        $merchTxnRef = $this->_null2unknown($_GET["vpc_MerchTxnRef"]);
        $transactionNo = $this->_null2unknown($_GET["vpc_TransactionNo"]);
        $acqResponseCode = $this->_null2unknown($_GET["vpc_AcqResponseCode"]);
        $txnResponseCode = $this->_null2unknown($_GET["vpc_TxnResponseCode"]);
        // 3-D Secure Data
        $verType = array_key_exists("vpc_VerType", $_GET) ? $_GET["vpc_VerType"] : "No Value Returned";
        $verStatus = array_key_exists("vpc_VerStatus", $_GET) ? $_GET["vpc_VerStatus"] : "No Value Returned";
        $token = array_key_exists("vpc_VerToken", $_GET) ? $_GET["vpc_VerToken"] : "No Value Returned";
        $verSecurLevel = array_key_exists("vpc_VerSecurityLevel", $_GET) ? $_GET["vpc_VerSecurityLevel"] : "No Value Returned";
        $enrolled = array_key_exists("vpc_3DSenrolled", $_GET) ? $_GET["vpc_3DSenrolled"] : "No Value Returned";
        $xid = array_key_exists("vpc_3DSXID", $_GET) ? $_GET["vpc_3DSXID"] : "No Value Returned";
        $acqECI = array_key_exists("vpc_3DSECI", $_GET) ? $_GET["vpc_3DSECI"] : "No Value Returned";
        $authStatus = array_key_exists("vpc_3DSstatus", $_GET) ? $_GET["vpc_3DSstatus"] : "No Value Returned";
        
        // *******************
        // END OF MAIN PROGRAM
        // *******************
        
        // FINISH TRANSACTION - Process the VPC Response Data
        // =====================================================
        // For the purposes of demonstration, we simply display the Result fields on a
        // web page.
        
        // Show 'Error' in title if an error condition
        $errorTxt = "";
        
        // Show this page as an error page if vpc_TxnResponseCode equals '7'
        if ($txnResponseCode == "7" || $txnResponseCode == "No Value Returned" || $errorExists) {
            $errorTxt = "Error ";
        }
        
        // This is the display title for 'Receipt' page 
        $title = $_GET["Title"];
        
        // The URL link for the receipt to do another transaction.
        // Note: This is ONLY used for this example and is not required for 
        // production code. You would hard code your own URL into your application
        // to allow customers to try another transaction.
        //TK//$againLink = URLDecode($_GET["AgainLink"]);
        
        
        $transStatus = "";
        if($hashValidated=="CORRECT" && $txnResponseCode=="0"){
        	$transStatus = "Giao dịch thành công";
        }elseif ($hashValidated=="INVALID HASH" && $txnResponseCode=="0"){
        	$transStatus = "Giao dịch Pendding";
        }else {
        	$transStatus = "Giao dịch thất bại";
        }
        
        $data['responseMessage'] = $this->_getResponseDescription2($txnResponseCode);
        $data['transStatus'] = $transStatus;
        $data['merchantID'] = $merchantID;
        $data['merchTxnRef'] = $merchTxnRef;
        $data['orderInfo'] = $orderInfo;
        $data['amount'] = $amount;
        $data['txnResponseCode'] = $txnResponseCode;
        $data['message'] = $message;
        $data['transactionNo'] = $transactionNo;
        
        if($hashValidated=="CORRECT" && $txnResponseCode=="0"){
            $this->load->model(array('usermodel', 'eventmodel'));
            $_SESSION['userLoggedIn']['point'] += $amount;
            $this->usermodel->update($_SESSION['userLoggedIn']['id'], array('point' => $_SESSION['userLoggedIn']['point']));
        }
        $this->session->set_flashdata('message', $transStatus);
        
        redirect('user/recharge');  
    }
    
    // This method uses the QSI Response code retrieved from the Digital
    // Receipt and returns an appropriate description for the QSI Response Code
    //
    // @param $responseCode String containing the QSI Response Code
    //
    // @return String containing the appropriate description
    //
     private  function _getResponseDescription2($responseCode) {
    	switch ($responseCode) {
          case "0" :
              $result = "Transaction Successful";
              break;
          case "?" :
              $result = "Transaction status is unknown";
              break;
          case "1" :
              $result = "Bank system reject";
              break;
          case "2" :
              $result = "Bank Declined Transaction";
              break;
          case "3" :
              $result = "No Reply from Bank";
              break;
          case "4" :
              $result = "Expired Card";
              break;
          case "5" :
              $result = "Insufficient funds";
              break;
          case "6" :
              $result = "Error Communicating with Bank";
              break;
          case "7" :
              $result = "Payment Server System Error";
              break;
          case "8" :
              $result = "Transaction Type Not Supported";
              break;
          case "9" :
              $result = "Bank declined transaction (Do not contact Bank)";
              break;
          case "A" :
              $result = "Transaction Aborted";
              break;
          case "C" :
              $result = "Transaction Cancelled";
              break;
          case "D" :
              $result = "Deferred transaction has been received and is awaiting processing";
              break;
          case "F" :
              $result = "3D Secure Authentication failed";
              break;
          case "I" :
              $result = "Card Security Code verification failed";
              break;
          case "L" :
              $result = "Shopping Transaction Locked (Please try the transaction again later)";
              break;
          case "N" :
              $result = "Cardholder is not enrolled in Authentication scheme";
              break;
          case "P" :
              $result = "Transaction has been received by the Payment Adaptor and is being processed";
              break;
          case "R" :
              $result = "Transaction was not processed - Reached limit of retry attempts allowed";
              break;
          case "S" :
              $result = "Duplicate SessionID (OrderInfo)";
              break;
          case "T" :
              $result = "Address Verification Failed";
              break;
          case "U" :
              $result = "Card Security Code Failed";
              break;
          case "V" :
              $result = "Address Verification and Card Security Code Failed";
              break;
  		case "99" :
              $result = "User Cancel";
              break;
          default  :
              $result = "Unable to be determined";
      }
      return $result;
    }
}